import service from "@/utils/request";
import { getToken } from "@/utils/auth";

export default {
  methods: {
    async $markSingleChatRead(chatId, recordContent, messageIds = []) {
      const unreadMsgs = recordContent.filter(
        (msg) => !msg.isMyselfMsg && msg.isRead === 0 && (messageIds.length === 0 || messageIds.includes(msg.id))
      );
      if (unreadMsgs.length === 0) return;

      // 本地先乐观更新
      unreadMsgs.forEach((msg) => {
        const index = recordContent.findIndex((item) => item.id === msg.id);
        if (index > -1) {
          recordContent[index].isRead = 1;
        }
      });

      try {
        await service({
          method: "post",
          url: "friend_chat/markMessageRead",
          data: {
            token: getToken(),
            friendId: chatId,
            messageIds: unreadMsgs.map((msg) => msg.id),
          },
        });
      } catch (error) {
        // 回滚
        unreadMsgs.forEach((msg) => {
          const index = recordContent.findIndex((item) => item.id === msg.id);
          if (index > -1) {
            recordContent[index].isRead = 0;
          }
        });
        throw error;
      }
    },

    $applyReadSync(recordContent, messageIdMap, receiverId, syncMessageIds) {
      syncMessageIds.forEach((msgId) => {
        const index = messageIdMap.get(msgId);
        if (index !== undefined && recordContent[index].isMyselfMsg) {
          recordContent[index].isRead = 1;
        }
      });
    },
  },
};
